package com.mf.service.authority.impl;

import com.mf.dao.authority.RoleInfoDao;
import com.mf.dao.authority.RoleResourceRelationDao;
import com.mf.dao.authority.UserRoleRelationDao;
import com.mf.domain.authority.RoleInfo;
import com.mf.domain.authority.RoleResourceRelation;
import com.mf.domain.authority.UserRoleRelation;
import com.mf.service.authority.RoleInfoService;
import com.mf.service.framework.GenericService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色信息Service层实现类
 * User: zhaoming
 * DateTime: 2016-07-14
 * To change this template use File | Settings | File Templates.
 **/
@Service
public class RoleInfoServiceImpl extends GenericService<RoleInfo> implements RoleInfoService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private RoleInfoDao roleInfoDao;
    @Resource
    private UserRoleRelationDao userRoleRelationDao;
    @Resource
    private RoleResourceRelationDao roleResourceRelationDao;

    /**
     * 根据主键删除角色信息
     * @param roleInfo 角色信息Domain
     */
    @Transactional
    public boolean deleteByPrimaryKey(RoleInfo roleInfo){

        roleInfo = roleInfoDao.selectByPrimaryKey(roleInfo);

        //删除与当前角色编码相关的用户信息
        UserRoleRelation userRoleRelation = new UserRoleRelation();
        userRoleRelation.setRoleCode(roleInfo.getRoleCode());
        List<UserRoleRelation> userRoleRelations = userRoleRelationDao.selectByCondition(userRoleRelation);
        userRoleRelationDao.deleteByPrimaryKeys(userRoleRelations);

        //删除与当前角色编码相关的资源信息
        RoleResourceRelation roleResourceRelation = new RoleResourceRelation();
        roleResourceRelation.setRoleCode(roleInfo.getRoleCode());
        List<RoleResourceRelation> roleResourceRelations = roleResourceRelationDao.selectByCondition(roleResourceRelation);
        roleResourceRelationDao.deleteByPrimaryKeys(roleResourceRelations);

        return roleInfoDao.deleteByPrimaryKey(roleInfo);
    }

    /**
     * 检查重复数据
     * @return 验证结果
     */
    public Map<String, Object> checkRepeat(RoleInfo roleInfo){
        Map<String, Object> map = new HashMap<>();
        List<RoleInfo> roleInfos = roleInfoDao.selectByCondition(roleInfo);
        if(CollectionUtils.isNotEmpty(roleInfos)){
            map.put("error", "重复数据");
        }else{
            map.put("ok", "");
        }
        return map;
    }


}
